package com.controller;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pojo.Department;
import com.service.IDepartmentService;
import com.util.Message;

@Controller
public class DepartmentController {
	@Resource
	private IDepartmentService departmentService;
	
	//分页
	@RequestMapping(value = "/allDepartmentsByPage", method = RequestMethod.POST)
	@ResponseBody
	public Message getdepartments(@RequestBody Message message) {
		List<Department> list=departmentService.getDepartments(Integer.valueOf(message.getMessage()),message.getGroups());
		//重新获取总数，保证数据事实刷新
		int count = departmentService.getCounts();
		Message mess=new Message();
		mess.setDepartment(list);
		mess.setMessage((int)Math.ceil((float)count/message.getGroups())+"");
		return mess;
	}
	
	@RequestMapping(value = "/allDepartments", method = RequestMethod.GET)
	@ResponseBody
	public List<Department> getalldepartments() {
		List<Department> list = departmentService.getDepartments();
		return list;
	}

	// 获取总页数
	@RequestMapping(value = "/getDepartmentCounts", method = RequestMethod.POST)
	@ResponseBody
	public Message getcounts(@RequestBody Message message) {
		// 获取总数
		int count = departmentService.getCounts();
		Message mess = new Message();
		mess.setMessage((int) Math.ceil((float) count / message.getGroups()) + "");
		return mess;
	}

	@RequestMapping(value = "/deleteDepartment/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public Message deletedepartment(@PathVariable int id) {
		departmentService.deleteDepartments(id);
		departmentService.deleteDepartment(id);
		return new Message("success");
	}

	@RequestMapping(value = "/addDepartment", method = RequestMethod.POST)
	@ResponseBody
	public Department adddepartment(@RequestBody Department d) {
		Department dt = departmentService.createDepartment(d);
		return dt;
	}

	@RequestMapping(value = "/updateDepartment", method = RequestMethod.PUT)
	@ResponseBody
	public Department updatedepartment(@RequestBody Department d) {
		Department dt = departmentService.updateDepartment(d);
		return dt;
	}
	
	@RequestMapping(value = "/getDepartment/{departmentid}", method = RequestMethod.GET)
	@ResponseBody
	public Department getDepartment(@PathVariable int departmentid) {
		Department d = departmentService.getDepartmentByid(departmentid);
		return d;
	}
}
